import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class  WelfareService {

    constructor( public http: Http) { }

    // 新闻列表
    getNews(params): Observable<any> {
      return this.http.get(ROOT_URL + 'news/index', {params})
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 新闻列表
    addNews(params): Observable<any> {
      return this.http.post(ROOT_URL + 'news/save', params)
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 新闻详情
    detailNews(params): Observable<any> {
      return this.http.get(ROOT_URL + 'news/details', {params})
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 新闻详情
    shelvesNews(params): Observable<any> {
      return this.http.put(ROOT_URL + 'news/shelves', params)
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 编辑新闻
    editNews(params): Observable<any> {
      return this.http.post(ROOT_URL + 'news/edit', params)
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 删除新闻
    deleteNews(params): Observable<any> {
      return this.http.delete(ROOT_URL + 'News/delete', {params})
        .map(this.extractData)
        .catch(this.handleError);
    }
    // 获取企业
    getEnterprise(params): Observable<any> {
      return this.http.get(ROOT_URL + 'User/enterprise', {params})
        .map(this.extractData)
        .catch(this.handleError);
    }

    private extractData(res: Response) {
        const body = res.json();
        if(body.code == 5003){
            // location.reload();
        }
        return body;
    }
    private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}
